// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package dao

import (
	"context"
	"encoding/json"
	"time"

	"gitcode.com/lvupclub/proto-gen-go.git/src/user_api"
	"github.com/redis/go-redis/v9"
)

const _CACHE_PREFIX_SESS = "sess:"

type SessionDbItem struct {
	SessionId string             `json:"sessionId"`
	UserId    string             `json:"userId"`
	UserType  user_api.USER_TYPE `json:"userType"`
}

type _CacheDao struct {
	rdb *redis.Client
}

func newCacheDao(rdb *redis.Client) (*_CacheDao, error) {
	err := rdb.ConfigSet(context.Background(), "notify-keyspace-events", "Ex").Err()
	if err != nil {
		return nil, err
	}
	return &_CacheDao{rdb: rdb}, nil
}

func (db *_CacheDao) SetSession(ctx context.Context, dbItem *SessionDbItem) error {
	data, err := json.Marshal(dbItem)
	if err != nil {
		return err
	}
	return db.rdb.SetEx(ctx, _CACHE_PREFIX_SESS+dbItem.SessionId, data, 24*time.Hour).Err()
}

func (db *_CacheDao) GetSession(ctx context.Context, sessionId string) (*SessionDbItem, bool) {
	data, err := db.rdb.Get(ctx, _CACHE_PREFIX_SESS+sessionId).Result()
	if err != nil {
		return nil, false
	}
	retItem := &SessionDbItem{}
	err = json.Unmarshal([]byte(data), retItem)
	if err != nil {
		return nil, false
	}
	return retItem, true
}

func (db *_CacheDao) RemoveSession(ctx context.Context, sessionId string) {
	db.rdb.Del(ctx, _CACHE_PREFIX_SESS+sessionId).Result()
}

func (db *_CacheDao) KeepSessionAlive(ctx context.Context, sessionId, userId string) {
	db.rdb.Expire(ctx, _CACHE_PREFIX_SESS+sessionId, 24*time.Hour).Result()
}
